package com.sunkyc.module.oss.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunkyc.commons.entity.TablePageData;
import com.sunkyc.framework.utils.TablePageDataBuilderUtil;
import com.sunkyc.commons.entity.PageQueryVo;
import com.sunkyc.module.oss.client.FileService;
import com.sunkyc.module.oss.entity.SysOss;
import com.sunkyc.module.oss.mapper.SysOssMapper;
import com.sunkyc.module.oss.service.SysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 云存储对象 服务实现类
 * </p>
 *
 * @author sunkyc
 * @since 2022-06-07
 */
@Service
@RequiredArgsConstructor
public class SysOssServiceImpl extends ServiceImpl<SysOssMapper, SysOss> implements SysOssService {
    private final  SysOssMapper baseMapper;

    private final FileService fileService;
    private final MultipartProperties multipartProperties;



    @Override
    public SysOss addFileUpload(SysOss sysOss) throws IOException {


        sysOss.setFileId(IdUtil.getSnowflakeNextId());
        baseMapper.insert(sysOss);
       return sysOss;
    }

    @Override
    public Long getUploadFileSize() {
        return multipartProperties.getMaxFileSize().toBytes();
    }

    @Override
    public TablePageData<SysOss> queryFileList(PageQueryVo pageQueryVo, SysOss sysOss) {
        Page<SysOss> page = new Page<>(pageQueryVo.getCurrent(),pageQueryVo.getPageSize());
        IPage<SysOss> iPage = baseMapper.selectPage(page,buildWrapper(sysOss));
        return TablePageDataBuilderUtil.buildTablePageData(iPage);
    }

    @Override
    public int delFile(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public List<SysOss> queryListByIds(Long[] ids) {
        return baseMapper.selectBatchIds(Arrays.asList(ids));
    }


    private Wrapper<SysOss> buildWrapper(SysOss sysOss){
       return Wrappers.lambdaQuery(SysOss.class)
                .like(StrUtil.isNotBlank(sysOss.getFileName()),SysOss::getFileName,sysOss.getFileName())
                .like(StrUtil.isNotBlank(sysOss.getFileOnceName()),SysOss::getFileOnceName,sysOss.getFileOnceName())
                .eq(StrUtil.isNotBlank(sysOss.getFileFomat()),SysOss::getFileFomat,sysOss.getFileFomat())
               .orderByDesc(SysOss::getCreateTime);
    }
}
